package capricornus.actor.controller
{
	import capricornus.actor.Actor;
	import capricornus.actor.attribute.ActorMovableAttribute;
	import capricornus.actor.events.ActorEvent;

	/**
	 * 追踪控制器 
	 * @author kael
	 */	
	public class ActorTrackController
	{
		/**
		 * 跟踪的最小距离 
		 */		
		protected var _minTrackLen:int;
		/**
		 *  _minTrackLen的平方值
		 */		
		protected var _minTrackLen2:int;
		
		protected var _actor:Actor;
		
		protected var _actorTrack:Actor;
		
		public function ActorTrackController( actor:Actor )
		{
			_actor = actor;
			init();
		}
		
		private function init():void
		{
			
		}
		
		/**
		 * 销毁 
		 */		
		public function destroy():void
		{
			clear();
		}
		
		/**
		 * 开始追踪 
		 * @param actor
		 */		
		public function track( actor:Actor ):void
		{
			clear();
			_actorTrack = actor;
			if( _actorTrack==null ) return;
			//寻路，这个根据场景定
			
			_minTrackLen = (actor.attribute as ActorMovableAttribute).trackValideLen + (_actorTrack.attribute as ActorMovableAttribute).hurtValideLen;
			_minTrackLen2 = _minTrackLen * _minTrackLen;
			//监听跟踪目标的移动消息
			_actorTrack.addEventListener( ActorEvent.MOVED, onActorTrackMoved, false, 0, true );
			_actorTrack.addEventListener( ActorEvent.ACTOR_DESTROYED, onActorDestroy, false, 0, true );
			_actor.addEventListener( ActorEvent.MOVED, onActorMoved, false, 0, true );
		}
		
		/**
		 * 停止跟踪 
		 */		
		public function clear():void
		{
			if( _actorTrack != null )
			{
				_actorTrack.removeEventListener( ActorEvent.MOVED, onActorTrackMoved );
				_actorTrack.removeEventListener( ActorEvent.ACTOR_DESTROYED, onActorDestroy );
				_actorTrack = null;
				
				_actor.removeEventListener( ActorEvent.MOVED, onActorMoved );
			}
		}
		
		/**
		 * 移动了 
		 * @param e
		 */		
		protected function onActorMoved( e:ActorEvent ):void
		{
			var x:int = _actor.x - _actorTrack.x;
			var y:int = _actor.y - _actorTrack.y;
			if( Math.abs(x) > _minTrackLen || Math.abs(y) > _minTrackLen )
			{
				
			}
			else
			{
				if( x*x + y*y <= _minTrackLen2 )
				{
					//追到了
					_actor.dispatchEvent( new ActorEvent( ActorEvent.TRACK_CATCH ) );
					clear();
				}
			}
		}
		
		/**
		 * 跟踪目标挂了，不用追了
		 * @param e
		 * 
		 */		
		protected function onActorDestroy( e:ActorEvent ):void
		{
			clear();
		}
		
		/**
		 * 跟踪目标移动了 
		 * @param e
		 * 
		 */		
		protected function onActorTrackMoved( e:ActorEvent ):void
		{
			
		}
	}
}













